from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from pyquery import PyQuery as pq
import time
import mysql.connector
import re
from datetime import datetime


# 启动EdgeDriver服务
options = webdriver.EdgeOptions()
options.add_experimental_option("excludeSwitches", ['enable-automation']) # 关闭自动测试状态显示 // 会导致浏览器报：请停用开发者模式
options.add_argument('--disable-sync')
driver = webdriver.Edge(options=options) # 把Edge设为selenium驱动的浏览器代理；
driver.maximize_window() # 窗口最大化
wait = WebDriverWait(driver,10)
 
# 数据库连接
db = mysql.connector.connect(user='test', password='123456abc',host='localhost', database='mall')
cursor = db.cursor()

pageStart = 1     # 爬取起始页
pageEnd = 2         # 爬取终止页
currentCategory=""   #当前搜索的商品分类

# 输入“关键词”，搜索，并进行首次爬取
def search_goods():
    try:
        print('正在搜索: ')
        driver.get('https://search.suning.com/%E5%90%8A%E5%B8%A6/')
        # time.sleep(10)           # 强制停止10秒，请在此时手动扫码登陆
        driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {"source": """Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"""})
       
        # 定位搜索框
        input = wait.until(EC.presence_of_element_located((By.XPATH, '//input[@id="searchKeywords"]')))
        input.clear()  # 清除搜索框并输入关键词
        input.send_keys(currentCategory[2])
        
        # 找到“搜索”按钮，输入关键字搜索
        submit = wait.until(EC.presence_of_element_located((By.XPATH, '//input[@id="searchSubmit"]')))
        # submit = wait.until(EC.presence_of_element_located((By.XPATH, "//button[contains(@onclick, \"search('key');return false;\")]")))
        submit.click()

        # 获取商品信息
        get_goods()
 
        # 翻页操作,暂时屏蔽，没测试通过
        # for i in range(pageStart + 1, pageEnd+1):
        #     page_turning(i)
 
    except TimeoutException:
        print("##############搜索异常#####################3: error")
        return search_goods(currentCategory[2],pageStart,pageEnd)
 
# 翻页函数
def page_turning(page_number):
    print('正在翻页: ', page_number)
    try:
        # 强制等待2秒后翻页
        time.sleep(2)
        # 找到“下一页”的按钮
        submit = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="pageContent"]/div[1]/div[3]/div[4]/div/div/button[2]')))
        submit.click()
        # 判断页数是否相等
        wait.until(EC.text_to_be_present_in_element((By.XPATH, '//*[@id="sortBarWrap"]/div[1]/div[2]/div[2]/div[8]/div/span/em'), str(page_number)))
        get_goods(page_number)
    except TimeoutException:
        print("###############翻页失败###############3: error")
        page_turning(page_number)
 
# 获取每一页的商品信息；
def get_goods():

    # 获取屏幕高度
    screen_height = driver.execute_script("return window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;")
    # 获取页面总高度
    total_height = driver.execute_script("return Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight);")
   
    # 模拟滚动
    scroll_interval = 1000  # 每次滚动的像素数
    current_height = screen_height
    while current_height < total_height:
        driver.execute_script(f"window.scrollTo(0, {current_height});")
        time.sleep(1)  # 等待图片加载
        current_height += scroll_interval
    time.sleep(3) # 获取商品前固定等待10秒,刷新/滑动界面，使所有信息都加载完成
    print("##########滑动中代码运行#################")
    
    # 提取所有商品的共同父元素的类选择器
    # 使用XPath定位所有name属性以"ssdsn_search_pro_name"开头的a标签
    elements = driver.find_elements(By.CLASS_NAME, "product-box")
    print("##########商品数量#################"+ str(len(elements)))
    
    for product_box in elements:
        # name = item.find_element(By.XPATH, "//a[starts-with(@name, 'ssdsn_search_pro_name')]").text  # 使用XPath定位所有name属性以"ssdsn_search_pro_name"开头的a标签
        # pic = item.find_element(By.XPATH, "//img[@tabindex='-1']").get_attribute('src')
        # priceStr = item.find_element(By.XPATH, "//span[@class='def-price']").text
        # price = priceStr.replace('¥', '')
        # print("##########name#################"+name)

        # 定位标题元素
        title_element = product_box.find_element(By.CSS_SELECTOR, ".title-selling-point a")
        # 获取标题文本
        name = title_element.text
        print(name)

        # 定位图片元素
        img_element = product_box.find_element(By.CSS_SELECTOR, ".res-img .img-block img")
        # 获取图片URL
        pic = img_element.get_attribute('src')
        print(pic)

        # 定位价格元素
        price_element = product_box.find_element(By.CSS_SELECTOR, ".price-box .def-price")
        # 获取价格文本
        price = re.sub(r'[^\d.]', '', price_element.text)
        print(price)

        product = {
            'brand_id': 0,                            # 品牌ID
            'product_category_id': currentCategory[0],                 # 产品所属的类别ID
            'feight_template_id': 0,                   # 运费模板ID
            'product_attribute_category_id': 0,        # 产品属性分类ID
            'name': name,   # 产品名称
            'pic': pic,  # 产品主图链接
            'product_sn': datetime.now().timestamp() * 1000,                   # 产品序列号
            'delete_status': 0,                        # 删除状态，0通常表示未删除
            'publish_status': 1,                       # 发布状态，1通常表示已发布
            'new_status': 0,                           # 新品状态，1通常表示新品
            'recommand_status': 1,                     # 推荐状态，1通常表示推荐
            'verify_status': 0,                        # 审核状态，0可能表示未审核
            'sort': 0,                                 # 排序权重
            'sale': 999,                                # 销售数量
            'price':price,                          # 当前价格
            'promotion_price': price,                # 促销价格
            'gift_growth': price,                       # 购买此产品获得的成长值
            'gift_point': price,                        # 购买此产品获得的积分
            'use_point_limit': 0,                      # 使用积分的限制
            'sub_title': '【限时限量抢购】[高性价]'+name+' [超值优惠]，已加入全方位服务计划，延保售后无忧。',   # 产品副标题
            'description':'【限时限量抢购】[高性价]'+name+' [超值优惠]，已加入全方位服务计划，延保售后无忧。',                           # 产品描述
            'original_price': price,                 # 原价
            'stock': 10000,                              # 库存量
            'low_stock': 100,                            # 低库存阈值
            'unit': '',                                # 单位
            'weight': 0.00,                            # 产品重量
            'preview_status': 0,                       # 预览状态
            'service_ids': '1,2,3',                    # 服务ID列表，用逗号分隔
            'keywords': '',                            # 搜索关键词
            'note': '',                                # 内部备注
            'album_pics': pic,                          # 图册图片链接列表
            'detail_title': '【限时限量抢购】[高性价]'+name+' [超值优惠]，已加入全方位服务计划，延保售后无忧。',         # 详情页标题
            'detail_desc': '【限时限量抢购】[高性价]'+name+' [超值优惠]，已加入全方位服务计划，延保售后无忧。',         # 详情页描述
            'detail_html': '<div><img src='+pic+' /> ...',  # 详情页HTML
            'detail_mobile_html': '<div><img src='+pic+' /> ...' ,                  # 移动端详情页HTML
            'promotion_start_time': '2024-10-01 15:12:54',  # 促销开始时间
            'promotion_end_time': '2024-10-07 00:00:00',    # 促销结束时间
            'promotion_per_limit': 0,                  # 促销每人限购数量
            'promotion_type': 1,                       # 促销类型，数字或枚举值
            'brand_name': '',                       # 品牌名称
            'product_category_name': currentCategory[2]         # 产品类别名称
        }
        # print(product)
        insert_product(product)                                         # 下一行

# 插入商品信息
def insert_product(product):
    add_product = (
        "INSERT INTO `mall`.`pms_product` "
        "(brand_id, product_category_id, feight_template_id, product_attribute_category_id, "
        "name, pic, product_sn, delete_status, publish_status, new_status, recommand_status, "
        "verify_status, sort, sale, price, promotion_price, gift_growth, gift_point, "
        "use_point_limit, sub_title, description, original_price, stock, low_stock, "
        "unit, weight, preview_status, service_ids, keywords, note, album_pics, "
        "detail_title, detail_desc, detail_html, detail_mobile_html, "
        "promotion_start_time, promotion_end_time, promotion_per_limit, promotion_type, "
        "brand_name, product_category_name) "
        "VALUES "
        "(%(brand_id)s, %(product_category_id)s, %(feight_template_id)s, %(product_attribute_category_id)s, "
        "%(name)s, %(pic)s, %(product_sn)s, %(delete_status)s, %(publish_status)s, %(new_status)s, "
        "%(recommand_status)s, %(verify_status)s, %(sort)s, %(sale)s, %(price)s, "
        "%(promotion_price)s, %(gift_growth)s, %(gift_point)s, %(use_point_limit)s, "
        "%(sub_title)s, %(description)s, %(original_price)s, %(stock)s, %(low_stock)s, "
        "%(unit)s, %(weight)s, %(preview_status)s, %(service_ids)s, %(keywords)s, "
        "%(note)s, %(album_pics)s, %(detail_title)s, %(detail_desc)s, %(detail_html)s, "
        "%(detail_mobile_html)s, %(promotion_start_time)s, %(promotion_end_time)s, "
        "%(promotion_per_limit)s, %(promotion_type)s, %(brand_name)s, "
        "%(product_category_name)s)"
    )
    cursor.execute(add_product, product)
    db.commit()

    # SQL查询语句
    query = "SELECT id FROM pms_product ORDER BY id DESC LIMIT 1"
    cursor.execute(query) 
    newProduct = cursor.fetchone()     # 获取查询结果
    latest_id = newProduct[0] if newProduct else None # 提取最新ID 
    print("Latest ID:", latest_id)   # 打印最新ID

    # 创建包含SKU库存信息的字典
    sku = {
        'product_id': latest_id,                          # 对应的产品ID
        'sku_code': 'SKU编码',             # SKU编码
        'price': product['price']  ,                          # 价格
        'stock': 10000,                               # 库存量
        'low_stock': 100,                         # 低库存警告阈值，这里使用None表示NULL
        'pic': product['pic']  ,                                # SKU图片链接，这里使用None表示NULL
        'sale':product['sale']  ,                            # 销售数量，这里使用None表示NULL
        'promotion_price': product['promotion_price']  ,                  # 促销价格
        'lock_stock': -8,                          # 锁定库存量
        'sp_data': '[{"key":"暂无","value":"暂无"}]'  # SKU属性数据，JSON格式
    }
    # 准备SQL语句以插入数据
    add_sku= (
        "INSERT INTO `mall`.`pms_sku_stock` "
        "(product_id, sku_code, price, stock, low_stock, pic, sale, promotion_price, lock_stock, sp_data) "
        "VALUES "
        "(%(product_id)s, %(sku_code)s, %(price)s, %(stock)s, %(low_stock)s, "
        "%(pic)s, %(sale)s, %(promotion_price)s, %(lock_stock)s, %(sp_data)s)"
    )
    # 执行SQL语句并提交事务
    cursor.execute(add_sku, sku)
    db.commit()

#入口
if __name__ == '__main__':

    # 获取所有二级商品分类
    cursor.execute("SELECT * FROM pms_product_category WHERE parent_id !=0 and id=178")
    results = cursor.fetchall()
    db.commit()     # 提交事务

    # 开始爬取数据
    for result in results:
        currentCategory=result
        try:
            print('#################当前搜索：##############33:', currentCategory[2])
            search_goods()
        except Exception as exc:
            print('获取数据异常:', exc)
 
  